package com.qs.javame.thread.tool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 测试：Semaphore（信号量）
 */
public class SemaphoreTest {

    //线程数
    private static final int THREAD_COUNT = 30;

    //线程池，初始化30个线程
    private static ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);

    //信号量，控制一次性只允许10个线程并发执行
    private static Semaphore semaphore = new Semaphore(10);

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    // System.out.println("剩余许可数：" + semaphore.availablePermits());
                    // System.out.println("正在获取许可的线程数：" + semaphore.getQueueLength());
                    System.out.println(Thread.currentThread().getName() + "save data");
                    TimeUnit.SECONDS.sleep(3);
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        executorService.shutdown();
    }
}
